package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.*;
import com.itheima.reggie.service.OrdersService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrdersMapper orderMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public void submit(Orders orders) {
        // 0、获取用户id
        Long userId = BaseContext.getCurrentId();

        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> qws = new LambdaQueryWrapper<>();
        qws.eq(userId != null, ShoppingCart::getUserId, userId);
        List<ShoppingCart> list = shoppingCartService.list(qws);

        // 2、查询用户数据 select * from user where id = ?
        User user = userMapper.selectById(userId);

        // 3、根据地址id查询地址数据 select * from address_book where id = ?
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());

        //订单号:雪花生成算法
        long orderId = IdWorker.getId();//订单号
        BigDecimal amount = new BigDecimal(0); //总价

        // 4、保存订单明细数据：点了哪些菜品或套餐
        for (ShoppingCart shoppingCart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);

            //orderId单独设置
            orderDetail.setOrderId(orderId);

            //amount金额单独设置,数量  *  单价
            BigDecimal price = shoppingCart.getAmount();
            BigDecimal number = new BigDecimal(shoppingCart.getNumber());
            orderDetail.setAmount(price.multiply(number));
           BigDecimal s =  orderDetail.getAmount();
            amount= amount.add(orderDetail.getAmount());
            orderDetailMapper.insert(orderDetail);
        }
       /* List<OrderDetail> collect = list.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);

            //orderId单独设置
            orderDetail.setOrderId(orderId);

            //amount金额单独设置,数量  *  单价
            BigDecimal price = item.getAmount();
            BigDecimal number = new BigDecimal(item.getNumber());
            orderDetail.setAmount(price.multiply(number));
            amount.add(orderDetail.getAmount());
            orderDetailMapper.insert(orderDetail);
            return orderDetail;
        }).collect(Collectors.toList());*/

        // 5、保存订单数据，有许多数据需要单独设置
        orders.setId(orderId);//订单id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(amount);//总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//收货人联系电话
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                        + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址
        orderMapper.insert(orders);
        // 6、删除当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartMapper.delete(queryWrapper);

    }
}
